package cc.vv.baselibrary.view.columnchart;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.DashPathEffect;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.PathEffect;
import android.graphics.Rect;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import cc.vv.baselibrary.R;
import cc.vv.baselibrary.server.HealthRecordPopupwindowServer;
import cc.vv.baselibrary.util.ColorUtil;
import cc.vv.baselibrary.util.LKCommonUtil;
import cc.vv.baselibrary.util.LKLogUtil;
import cc.vv.baselibrary.view.columnchart.bean.ShowPopwinDataObj;

/**
 * 柱状图月控件
 * Created by Hankkin on 16/12/11.
 * 注释:参考MyChartView原理相
 * 月  30天（28,29,31）
 */

public class SingleViewMonth extends View {


    private Paint mPaint, mChartPaint;

    private Rect mBound;

    private int mStartWidth;

    private int mHeight;

    private int mChartWidth;

    private int mSize;

    private int leftColor;

    private int lefrColorBottom;

    private int selectLeftColor;

    private int lineColor;
    private int zongjuli;

    private double numMax = 100f;

    //Y轴中间值
    private double numMiddle = numMax / 2;

    //Y轴最低值
    private double numBottom = numMax / 3;

    /**
     * 虚线与上面的字符之间的间距
     */
    private int linesAndNumberSpace = 10;

    /**
     * 底部的间距
     */
    private int bottomSpace = 98;

    /**
     * 单位
     */
    private String unit = "";

    private Double taraetNum = 0.0;

    private int defaultColor = ColorUtil.setBCColor(R.color.color_28BFA9);

    /**
     * 关闭所有popuWindow
     */
    public void dismissPopuWindow() {
        if (popupWindow != null && popupWindowline != null) {
            popupWindow.dismiss();
            popupWindowline.dismiss();
        }
    }

    /**
     * 总天数
     */
    private int totalDays;

    public void setList(List<ShowPopwinDataObj> list, double numMax, View mOutView, int totalDays) {
        this.mOutView = mOutView;
        this.list = list;
        this.numMax = numMax;
        this.numMiddle = numMax * 2 / 3;
        this.numBottom = numMax / 3;
        this.totalDays = totalDays;
        invalidate();
    }

    public void setList(List<ShowPopwinDataObj> list, double numMax, View mOutView, int totalDays, String unit) {
        this.mOutView = mOutView;
        this.list = list;
        this.numMax = numMax;
        this.numMiddle = numMax * 2 / 3;
        this.numBottom = numMax / 3;
        this.totalDays = totalDays;
        this.unit = unit;
        invalidate();
    }

    public void setList(List<ShowPopwinDataObj> list, Double taraetNum, double numMax, View mOutView, int totalDays, String unit) {
        this.mOutView = mOutView;
        this.list = list;
        this.numMax = numMax;
        this.numMiddle = numMax * 2 / 3;
        this.numBottom = numMax / 3;
        this.totalDays = totalDays;
        this.unit = unit;
        this.taraetNum = taraetNum;
        invalidate();
    }

    public SingleViewMonth(Context context) {
        this(context, null);
    }

    public SingleViewMonth(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SingleViewMonth(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        TypedArray array = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyChartView, defStyleAttr, 0);
        int n = array.getIndexCount();
        for (int i = 0; i < n; i++) {
            int attr = array.getIndex(i);
            if (attr == R.styleable.MyChartView_xyColor) {
                lineColor = array.getColor(attr, defaultColor);
            } else if (attr == R.styleable.MyChartView_leftColor) {
                // 默认颜色设置为黑色
                leftColor = array.getColor(attr, defaultColor);
            } else if (attr == R.styleable.MyChartView_leftColorBottom) {
                lefrColorBottom = array.getColor(attr, defaultColor);
            } else if (attr == R.styleable.MyChartView_selectLeftColor) {
                // 默认颜色设置为黑色
                selectLeftColor = array.getColor(attr, defaultColor);
            } else {
                bringToFront();
            }
//            switch (attr) {
//                case R.styleable.MyChartView_xyColor:
//                    lineColor = array.getColor(attr, Color.BLACK);
//                    break;
//                case R.styleable.MyChartView_leftColor:
//                    // 默认颜色设置为黑色
//                    leftColor = array.getColor(attr, Color.BLACK);
//                    break;
//                case R.styleable.MyChartView_leftColorBottom:
//                    lefrColorBottom = array.getColor(attr, Color.BLACK);
//                    break;
//                case R.styleable.MyChartView_selectLeftColor:
//                    // 默认颜色设置为黑色
//                    selectLeftColor = array.getColor(attr, Color.BLACK);
//                    break;
//                default:
//                    bringToFront();
//            }
        }
        array.recycle();
        init();
    }


    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        if (totalDays == 0) {
            return;
        }
        mHeight = 0;
        mStartWidth = 0;
        zongjuli = 0;
        mSize = 0;
        mChartWidth = 0;
        mHeight = getHeight();
        zongjuli = getWidth() - getWidth() / 12;
        mSize = zongjuli / list.size();
        mStartWidth = 100;
        mChartWidth = mStartWidth;

        mPaint.setColor(lineColor);
        //画线
        canvas.drawLine(100, mHeight - 98, getWidth(), mHeight - 98, mPaint);


        //每隔的高度(numMax位置)
        double viewHight = ((double) mHeight - 150) / numMax;
        Paint paintHight = new Paint();
        paintHight.setTextAlign(Paint.Align.CENTER);
        paintHight.setStyle(Paint.Style.STROKE);
        paintHight.setColor(Color.parseColor("#CCCCCC"));
        paintHight.setTextSize(35);
        PathEffect effectsHight = new DashPathEffect(new float[]{8, 8, 8, 8}, 1);
        paintHight.setPathEffect(effectsHight);
        Path pathHight = new Path();
//        //画高虚线
//        pathHight.moveTo(getWidth() / 24, mHeight - 98 - (float) (numMax * viewHight));
//        pathHight.lineTo(getWidth() - (getWidth() / 24), mHeight - 98 - (float) (numMax * viewHight));
//        canvas.drawPath(pathHight, paintHight);
//        canvas.drawText((int)numMax+"", getWidth() - getWidth() / 12,
//                mHeight - 98 - (float) (numMax * viewHight) - 20, paintHight);
//
//        //画中虚线
//        pathHight.moveTo(getWidth() / 24, mHeight - 98 - (float) (numMiddle * viewHight));
//        pathHight.lineTo(getWidth() - (getWidth() / 24), mHeight - 98 - (float) (numMiddle * viewHight));
//        canvas.drawPath(pathHight, paintHight);
//        canvas.drawText((int)numMiddle+"", getWidth() - getWidth() / 12,
//                mHeight - 98 - (float) (numMiddle * viewHight) - 20, paintHight);
//
//        //画低虚线
//        pathHight.moveTo(getWidth() / 24, mHeight - 98 - (float) (numBottom * viewHight));
//        pathHight.lineTo(getWidth() - (getWidth() / 24), mHeight - 98 - (float) (numBottom * viewHight));
//        canvas.drawPath(pathHight, paintHight);
//        canvas.drawText((int)numBottom+"", getWidth() - getWidth() / 12,
//                mHeight - 98 - (float) (numBottom * viewHight) - 20, paintHight);

        //画高虚线
        pathHight.moveTo(mStartWidth, mHeight - bottomSpace - (float) (numMax * viewHight));
        pathHight.lineTo(getWidth(), mHeight - bottomSpace - (float) (numMax * viewHight));
        canvas.drawPath(pathHight, paintHight);
        canvas.drawText((int) numMax + "", 50,
                mHeight - bottomSpace - (float) (numMax * viewHight) + 14, paintHight);

        //画中虚线
        pathHight.moveTo(mStartWidth, mHeight - bottomSpace - (float) (numMiddle * viewHight));
        pathHight.lineTo(getWidth(), mHeight - bottomSpace - (float) (numMiddle * viewHight));
        canvas.drawPath(pathHight, paintHight);
        canvas.drawText((int) numMiddle + "", 50,
                mHeight - bottomSpace - (float) (numMiddle * viewHight) + 14, paintHight);

        //画低虚线
        pathHight.moveTo(mStartWidth, mHeight - bottomSpace - (float) (numBottom * viewHight));
        pathHight.lineTo(getWidth(), mHeight - bottomSpace - (float) (numBottom * viewHight));
        canvas.drawPath(pathHight, paintHight);
        canvas.drawText((int) numBottom + "", 50,
                mHeight - bottomSpace - (float) (numBottom * viewHight) + 14, paintHight);

        //绘制目标线
        if (taraetNum < numMax &&taraetNum > 0) {
            Paint paintHight1 = new Paint();
            paintHight1.setTextAlign(Paint.Align.CENTER);
            paintHight1.setStyle(Paint.Style.STROKE);
            paintHight1.setColor(defaultColor);
            paintHight1.setStrokeWidth(5f);
            PathEffect effectsHight1 = new DashPathEffect(new float[]{8, 8, 8, 8}, 1);
            paintHight1.setPathEffect(effectsHight1);
            Path pathHight1 = new Path();
            pathHight1.moveTo(mStartWidth, mHeight - bottomSpace - (float) (taraetNum * viewHight));
            pathHight1.lineTo(getWidth(), mHeight - bottomSpace - (float) (taraetNum * viewHight));
            canvas.drawPath(pathHight1, paintHight1);
        }
        //画数字
        for (int i = 1; i <= totalDays; i++) {
            mPaint.setTextSize(30);
            mPaint.setTextAlign(Paint.Align.CENTER);
            mPaint.getTextBounds(String.valueOf(i + 1) + "", 0, String.valueOf(i).length(), mBound);
            switch (i) {
                case 1:
                case 10:
                case 20:
                case 30:
                    if (i == 1) {
                        canvas.drawText("0" + (i), mStartWidth,
                                mHeight - 60 + mBound.height() * 1 / 2, mPaint);
                    } else {
                        canvas.drawText((i) + "", mStartWidth,
                                mHeight - 60 + mBound.height() * 1 / 2, mPaint);
                    }
                default:
                    break;
            }
            mStartWidth += zongjuli / totalDays;
        }

        //每隔的高度
        double sizeHight = ((double) mHeight - 150) / numMax;
        selectIndexRectF.clear();
        mChartPaint.setStyle(Paint.Style.FILL);
        mChartPaint.setColor(leftColor);
        if (list == null) {
            return;
        }
        //画柱状图
        for (int i = 0; i < list.size(); i++) {
            if (list.size() > 0) {
                double aFloat_1 = list.get(i).getValueData();
                double aFloat_2 = list.get(i).getValueData_2();
                if (aFloat_1 > numMax) {
                    aFloat_1 = numMax + 20;
                    aFloat_2 = numMax + 20;
                }
                double minAFloat = Math.min(aFloat_1, aFloat_2);
                double maxAFloat = Math.max(aFloat_1, aFloat_2);

                //先绘制高值, 低值数据绘制在前, 集合中保存高值矩形
                //绘制高值数据
                mChartPaint.setColor(defaultColor);
                RectF rectF = new RectF();
                rectF.left = mChartWidth - 10;
                rectF.right = mChartWidth + 10;
                rectF.bottom = mHeight - 98;
                rectF.top = mHeight - 98 - (float) (maxAFloat * sizeHight);
                canvas.drawRoundRect(rectF, 10, 10, mChartPaint);
                selectIndexRectF.add(rectF);
                //绘制低值数据
                if (minAFloat > 0) {
                    mChartPaint.setColor(Color.parseColor("#70C887"));
                    RectF rectF2 = new RectF();
                    rectF2.left = mChartWidth - 10;
                    rectF2.right = mChartWidth + 10;
                    rectF2.bottom = mHeight - 98;
                    rectF2.top = mHeight - 98 - (float) (minAFloat * sizeHight);
                    canvas.drawRect(rectF2, mChartPaint);
                }
                if (aFloat_1 > 1) {
                    RectF rectF1 = new RectF();
                    rectF1.left = mChartWidth - 10;
                    rectF1.right = mChartWidth + 10;
                    rectF1.bottom = mHeight - 98;
                    rectF1.top = mHeight - 105;
                    canvas.drawRoundRect(rectF1, 0, 0, mChartPaint);
                }
                mChartWidth += zongjuli / list.size();
            }
        }
    }


    /**
     * 初始化画笔等
     */
    private void init() {
        mPaint = new Paint();
        mPaint.setAntiAlias(true);
        mBound = new Rect();
        mChartPaint = new Paint();
        mChartPaint.setAntiAlias(true);
        contentView = View.inflate(context, R.layout.layout_pop_window_showdata, null);
        tv_hdp_data = (TextView) contentView.findViewById(R.id.tv_hdp_data);
        tv_hdp_time = (TextView) contentView.findViewById(R.id.tv_hdp_time);
        tv_hdp_value = (TextView) contentView.findViewById(R.id.tv_hdp_value);
        tv_hdp_unitj = (TextView) contentView.findViewById(R.id.tv_hdp_unit);
        contentViewline = View.inflate(context, R.layout.layout_pop_window_showdata_line, null);
    }


    private List<ShowPopwinDataObj> list = new ArrayList<>();

    private Context context;

    private View contentView;
    private View contentViewline;

    /**
     * 月日
     */
    private TextView tv_hdp_data;

    /**
     * 具体时间
     */
    private TextView tv_hdp_time;
    /**
     * 数值
     */
    private TextView tv_hdp_value;

    /**
     * 单位
     */
    private TextView tv_hdp_unitj;


    private View mOutView;

    private int x;

    private int y;
    private PopupWindow popupWindow;
    private PopupWindow popupWindowline;

    /**
     * 柱形图RectF列表
     */
    private List<RectF> selectIndexRectF = new ArrayList<>();


    private int position;

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        // 点击时获取的X坐标点
        x = (int) ev.getX();
        // 点击时获取的Y坐标点
        y = (int) ev.getY();
        if (list == null || list.size() == 0) {
            return super.onTouchEvent(ev);
        }
        for (int i = 0; i < selectIndexRectF.size(); i++) {
            ShowPopwinDataObj showPopwinDataObj = list.get(i);
            position = i;
            RectF rectF = selectIndexRectF.get(i);
            int left = (int) rectF.left;
            int right = (int) rectF.right;
            int bottom = (int) rectF.bottom;
            int top = (int) rectF.top;
            //判断区域
            boolean boolX = (left - CIRCLE_SIZE) < x && x < (right + CIRCLE_SIZE);
            boolean boolY = (top - CIRCLE_SIZE) < y && y < (bottom + CIRCLE_SIZE);
            if (rectF.contains(x, y) || (boolX && boolY)) {
                LKLogUtil.e("result答应数据==" + i);
                //中心点x的位置
                int xMiddle = (int) (rectF.left + (rectF.right - rectF.left) / 2) - LKCommonUtil.dip2px(1);
                int xStart = xMiddle - LKCommonUtil.dip2px(69) + 4;
                float posiXX = mHeight - 98 - (float) (numMax * (((double) mHeight - 150) / numMax) + LKCommonUtil.dip2px(16));
                float linePosiYY = mHeight - 98 - (float) (numMax * (((double) mHeight - 150) / numMax) - LKCommonUtil.dip2px(16));

                if (showPopwinDataObj != null && showPopwinDataObj.getValueData() != 0) {
                    if (popupWindow != null) {
                        // 弹窗不为空时进行是否显示判断，避免重复显示。由于点击时获取的坐标点不止一个
                        boolean isShowing = popupWindow.isShowing();
                        if (!isShowing) {
                            showPopupWindow(mOutView, xStart, (int) (posiXX), position);
                            showPopupWindowLine(mOutView, xMiddle, (int) (linePosiYY));
                        }
                    } else {
                        // 第一次弹窗为空，直接显示
                        showPopupWindow(mOutView, xStart, (int) (posiXX), position);
                        showPopupWindowLine(mOutView, xMiddle, (int) (linePosiYY));
                    }
                }
                break;
            }
        }
        return super.onTouchEvent(ev);
    }

    /**
     * 显示弹窗在指定控件下方的指定坐标点
     *
     * @param view 指定控件下方
     * @param x    横坐标
     * @param y    纵坐标
     */
    private void showPopupWindow(View view, int x, int y, int position) {
        ShowPopwinDataObj showPopwinDataObj = list.get(position);
        if (showPopwinDataObj != null) {
            //设置数据
            tv_hdp_data.setText(showPopwinDataObj.getMonthStr());
            HealthRecordPopupwindowServer.getInstance().setHealthRecordData(tv_hdp_value, tv_hdp_unitj,
                    showPopwinDataObj);
            if (showPopwinDataObj.getValueData() == 0.0) {
                return;
            }
        }

        // 创建弹窗指定大小
        popupWindow = new PopupWindow(contentView, FrameLayout.LayoutParams.WRAP_CONTENT,
                FrameLayout.LayoutParams.WRAP_CONTENT, true);
        popupWindow.setOutsideTouchable(true);
        // 设置弹窗的背景
        popupWindow.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.transparent_background));


        // 在指定位置显示弹窗
        popupWindow.showAsDropDown(view, x, y);


        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (popupWindowline != null && popupWindowline.isShowing()) {
                    popupWindowline.dismiss();
                }
            }
        });
    }


    private void showPopupWindowLine(View view, int x, int y) {
        ShowPopwinDataObj showPopwinDataObj = list.get(position);
        if (showPopwinDataObj != null) {
            if (showPopwinDataObj.getValueData() == 0.0) {
                return;
            }
        }
        // 创建弹窗指定大小
        popupWindowline = new PopupWindow(contentViewline, LKCommonUtil.dip2px(3),
                (mHeight - 98 - LKCommonUtil.dip2px(32)),
                true);
        popupWindowline.setOutsideTouchable(true);
        // 设置弹窗的背景
        popupWindowline.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.transparent_background));

        // 在指定位置显示弹窗

        popupWindowline.showAsDropDown(view, x, y);

        popupWindowline.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
            }
        });
    }


    /**
     * 公共部分
     */
    private static final int CIRCLE_SIZE = 20;
}
